package mdt.action;

import org.tigris.gef.base.Editor;
import org.tigris.gef.base.ModeCreate;
import org.tigris.gef.presentation.Fig;
import org.tigris.gef.presentation.FigDiamond;
import mdt.figure.FigDiamondChoice;
import mdt.model.DiamondChoice;

import java.awt.*;
import java.awt.event.MouseEvent;

/**
 * Created by xiaobyu on 7/15/2016.
 */
public class ModeCreateDiamondChoice extends ModeCreate {
    private FigDiamond diamond;
    private final int MIN_LEN = Editor.GRIP_SIZE * 4;
    public Fig createNewItem(MouseEvent me, int snapX, int snapY) {
        diamond = new FigDiamond(snapX, snapY - MIN_LEN / 2, MIN_LEN, MIN_LEN);
        //diamond.addPoint(snapX, snapY); //add the point twice
        FigDiamondChoice dc = new FigDiamondChoice(new DiamondChoice(), diamond);

        return dc;
    }

    public void mouseReleased(MouseEvent me) {
        if (me.isConsumed()) {
            return;
        }
        editor.damageAll();
        editor.add(_newItem);
        editor.getSelectionManager().select(_newItem);
        _newItem = null;
        done();
        me.consume();
    }

    public void mouseMoved(MouseEvent me) {
        mouseDragged(me);
    }

    public void mouseDragged(MouseEvent me) {
        if (me.isConsumed() || diamond == null) {
            return;
        }
        int x = me.getX(), y = me.getY();

        editor.damageAll();
        Point snapped = new Point(x, y);
        editor.snap(snapped);
        if (Math.abs(snapped.getX() - anchorX) < MIN_LEN / 2) {
            snapped.x += MIN_LEN / 2 * (snapped.getX() - anchorX > 0 ? 1 : -1);
        }
        if (Math.abs(snapped.getY() - anchorY) < MIN_LEN / 2) {
            snapped.y += MIN_LEN / 2 * (snapped.getY() - anchorY > 0 ? 1 : -1);
        }
        int w = (snapped.x - anchorX) * 2;
        int h = (snapped.y - anchorY) * 2;

        //diamond.setBounds(new Rectangle(anchorX, anchorY - h/2, w, h));
        Rectangle bounds = new Rectangle(anchorX, anchorY - h/2, w, h);
        if (bounds.width < 0) {
            bounds.width = -bounds.width;
            bounds.x -= bounds.width;
        }
        if (bounds.height < 0) {
            bounds.height = -bounds.height;
            bounds.y -= bounds.height;
        }
        _newItem.setBounds(bounds);
        editor.damageAll();
        me.consume();
    }
}
